//
//  RKSwipeBetweenViewControllers.m
//  RKSwipeBetweenViewControllers
//
//  Created by Richard Kim on 7/24/14.
//  Copyright (c) 2014 Richard Kim. All rights reserved.
//
//  @cwRichardKim for regular updates


#import "RKSwipeBetweenViewControllers.h"
#import "SMPageControl.h"
#import "EasePageViewController.h"
#import "WriteHelpViewController.h"
#import "WFPopTwoView.h"
#import "KxMenu.h"

@interface RKSwipeBetweenViewControllers ()

@property (nonatomic) UIScrollView *pageScrollView;
@property (nonatomic) NSInteger currentPageIndex;
@property (nonatomic) BOOL isPageScrollingFlag;
@property (nonatomic, strong) SMPageControl *pageControl;
@property (strong, nonatomic) UIScrollView *buttonContainer;

@property (strong, nonatomic) UIViewController *p_displayingViewController;
@property (strong, nonatomic) UISegmentedControl *segmentedControl;
@property (strong, nonatomic) WFPopView *operationView;

@end

@implementation RKSwipeBetweenViewControllers
@synthesize viewControllerArray;
@synthesize pageController;

+ (instancetype)newSwipeBetweenViewControllers{
    EasePageViewController *pageController = [[EasePageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    return [[RKSwipeBetweenViewControllers alloc] initWithRootViewController:pageController];
}

- (UIViewController *)curViewController{
    if (self.viewControllerArray.count > self.currentPageIndex) {
        return [self.viewControllerArray objectAtIndex:self.currentPageIndex];
    }else{
        return nil;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationBar.translucent = NO;
    viewControllerArray = [[NSMutableArray alloc]init];
    self.currentPageIndex = 0;
    self.isPageScrollingFlag = NO;
}
    
-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
    //    return UIStatusBarStyleDefault;
}

-(void)setupSegmentButtons {

    if (!_segmentedControl) {
        
        _segmentedControl = ({
            UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"本村", @"本县",@"本市"]];
            [segmentedControl setWidth:60 forSegmentAtIndex:0];
            [segmentedControl setWidth:60 forSegmentAtIndex:1];
            [segmentedControl setWidth:60 forSegmentAtIndex:2];
            [segmentedControl setTitleTextAttributes:@{
                                                       NSFontAttributeName: [UIFont boldSystemFontOfSize:16],
                                                       NSForegroundColorAttributeName: [UIColor colorWithHexString:@"0xc01a21"]
                                                       }
                                            forState:UIControlStateSelected];
            [segmentedControl setTitleTextAttributes:@{
                                                       NSFontAttributeName: [UIFont boldSystemFontOfSize:16],
                                                       NSForegroundColorAttributeName: [UIColor whiteColor]
                                                       } forState:UIControlStateNormal];
            [segmentedControl addTarget:self action:@selector(choosePlaceClick:) forControlEvents:UIControlEventValueChanged];
            segmentedControl;
        });
        _segmentedControl.selectedSegmentIndex=0;
    }
    pageController.navigationController.navigationBar.topItem.titleView = _segmentedControl;
}

- (void)choosePlaceClick:(id)sender{
    
    UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
    __weak typeof(self) weakSelf = self;
    [pageController setViewControllers:@[[viewControllerArray objectAtIndex:segmentedControl.selectedSegmentIndex]] direction:segmentedControl.selectedSegmentIndex>self.currentPageIndex?0:1 animated:YES completion:^(BOOL complete){
            if (complete) {
                weakSelf.currentPageIndex = segmentedControl.selectedSegmentIndex;
            }
    }];
}

-(void)viewWillAppear:(BOOL)animated {
    if (!pageController) {
        [self setupPageViewController];
        [self setupSegmentButtons];
        [self updateNavigationViewWithPercentX:self.currentPageIndex];
    }
}

-(void)setupPageViewController {
    if ([self.topViewController isKindOfClass:[UIPageViewController class]]) {
        pageController = (UIPageViewController*)self.topViewController;
        pageController.delegate = self;
        pageController.dataSource = self;
        [pageController setViewControllers:@[[viewControllerArray objectAtIndex:0]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
        [self syncScrollView];
        
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        rightBtn.frame = CGRectMake(0, 0, 25, 20);
        [rightBtn setImage:[UIImage imageNamed:@"writetopicimg"] forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(writeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        pageController.navigationItem.rightBarButtonItem=rightBarItem;
    }
}

-(void)syncScrollView {
    for (UIView* view in pageController.view.subviews){
        if([view isKindOfClass:[UIScrollView class]]) {
            self.pageScrollView = (UIScrollView *)view;
            self.pageScrollView.delegate = self;
            self.pageScrollView.scrollsToTop = YES;
        }
    }
}

-(void)updateCurrentPageIndex:(int)newIndex {
    self.currentPageIndex = newIndex;
}

- (void)setCurrentPageIndex:(NSInteger)currentPageIndex{
    _currentPageIndex = currentPageIndex;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
 
}

- (void)updateNavigationViewWithPercentX:(CGFloat)percentX{
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Page View Controller Data Source

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    _p_displayingViewController = viewController;
    NSInteger index = [self indexOfController:viewController];
    
    if ((index == NSNotFound) || (index == 0)) {
        return nil;
    }
    
    index--;
    return [viewControllerArray objectAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    _p_displayingViewController = viewController;
    NSInteger index = [self indexOfController:viewController];
    
    if (index == NSNotFound) {
        return nil;
    }
    index++;
    
    if (index == [viewControllerArray count]) {
        return nil;
    }
    return [viewControllerArray objectAtIndex:index];
}

-(void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {
    _p_displayingViewController = nil;
    if (completed) {
        self.currentPageIndex = [self indexOfController:[pageViewController.viewControllers lastObject]];
        _segmentedControl.selectedSegmentIndex=self.currentPageIndex;
    }
}

-(NSInteger)indexOfController:(UIViewController *)viewController {
    for (int i = 0; i<[viewControllerArray count]; i++) {
        if (viewController == [viewControllerArray objectAtIndex:i])
        {
            return i;
        }
    }
    return NSNotFound;
}

#pragma mark - Scroll View Delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isPageScrollingFlag = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.isPageScrollingFlag = NO;
}

- (void)writeBtnClick{
    
    [KxMenu setTitleFont:[UIFont systemFontOfSize:16]];
    NSArray *menuItems = @[
                               [KxMenuItem menuItem:@"发布话题" image:[UIImage imageNamed:@"writetopic"] target:self action:@selector(goToTopicController)],
                               [KxMenuItem menuItem:@"发布帮忙" image:[UIImage imageNamed:@"writehelp"] target:self action:@selector(goToHelpController)],
                               ];
    CGRect senderFrame = CGRectMake([UIScreen mainScreen].bounds.size.width - 35, 66, 0, 0);
    [KxMenu showMenuInView:self.view
                      fromRect:senderFrame
                     menuItems:menuItems];
}

-(void)goToHelpController{
    
    WriteHelpViewController *writeVC=[[WriteHelpViewController alloc]init];
    writeVC.hidesBottomBarWhenPushed=YES;
    writeVC.navTitle=@"发布帮忙";
    [self pushViewController:writeVC animated:YES];
}

-(void)goToTopicController{
    
    WriteHelpViewController *writeVC=[[WriteHelpViewController alloc]init];
    writeVC.hidesBottomBarWhenPushed=YES;
    writeVC.navTitle=@"发布话题";
    [self pushViewController:writeVC animated:YES];
}

@end
